﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//using BySoft.Server.Business.UserCode;
using BySoft.Server.Common.Enum;
using BySoft.Server.Business;
using BySoft.Web.Utility;
using BySoft.Server.Common.Entity;
using BySoft.Server.Consts;
using BySoft.Server.Common;
using System.Data;
using OneSoft.EntityCore;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Text;

namespace BySoft.Web.Site.ComPage
{
    public partial class DownloadFile : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    string strFileName = Server.UrlDecode(UIHelper.GetQueryStringValue("mc"));
                    string strFileActName = Server.UrlDecode(UIHelper.GetQueryStringValue("name"));
                    string strIsDel = Server.UrlDecode(UIHelper.GetQueryStringValue("isdel"));
                    string encodefileName = ToHexString(strFileActName);
                    //string encodefileName = strFileActName;


                    System.IO.FileStream r = new System.IO.FileStream(strFileName, System.IO.FileMode.Open);    //文件下载实例化
                    //设置基本信息  
                    Response.Buffer = false;
                    Response.AddHeader("Connection", "Keep-Alive");
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + encodefileName); // 此处文件名如果是中文在浏览器默认是筹码,应该加HttpUtility.UrlEncode(filename)
                    Response.AddHeader("Content-Length", r.Length.ToString());
                    while (true)    //如果文件大于缓冲区，通过while循环多次加载文件
                    {
                        //开辟缓冲区空间 
                        byte[] buffer = new byte[1024];  //读取文件的数据  
                        int leng = r.Read(buffer, 0, 1024);
                        if (leng == 0)             //到文件尾，结束  
                            break;
                        if (leng == 1024)            //读出的文件数据长度等于缓冲区长度，直接将缓冲区数据写入 
                            Response.BinaryWrite(buffer);           //向客户端发送数据流
                        else
                        {
                            //读出文件数据比缓冲区小，重新定义缓冲区大小，只用于读取文件的最后一个数据块 
                            byte[] b = new byte[leng]; for (int i = 0; i < leng; i++)
                                b[i] = buffer[i];
                            Response.BinaryWrite(b);
                        }
                    }
                    r.Close();//关闭下载文件 
                    if (strIsDel.Equals("1"))
                    {
                        DelFile(strFileName);
                    }
                    Response.End();//结束文件下载
                }
                catch { }
            }
               
        }

        private void DelFile(string strFileName)
        {
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
            }
        }

        public string ToHexString(string s)
        {
            char[] chars = s.ToCharArray();
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < chars.Length; index++)
            {
                bool needToEncode = NeedToEncode(chars[index]);
                if (needToEncode)
                {
                    string encodedString = ToHexString(chars[index]);
                    builder.Append(encodedString);
                }
                else
                {
                    builder.Append(chars[index]);
                }
            }

            return builder.ToString();
        }

        /// <summary>
        /// Determines if the character needs to be encoded.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private bool NeedToEncode(char chr)
        {
            string reservedChars = "$-_.+!*'(),@=&";

            if (chr > 127)
                return true;
            if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
                return false;

            return true;
        }

        /// <summary>
        /// Encodes a non-US-ASCII character.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private string ToHexString(char chr)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            byte[] encodedBytes = utf8.GetBytes(chr.ToString());
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < encodedBytes.Length; index++)
            {
                builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
            }

            return builder.ToString();
        }
    }
}